from flask import Flask
import os
import time
from Config import Configs
import logging
from extensions import ext_database
from extensions import ext_migrate
from extensions.ext_database import db
from models.serp import SerpResult
from flask_cors import CORS
from flask import json
import datetime

if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
    from gevent import monkey

    monkey.patch_all()
    # if os.environ.get("VECTOR_STORE") == 'milvus':
    import grpc.experimental.gevent

    grpc.experimental.gevent.init_gevent()


# 定义flask应用名称，并完全继承
class SerpNews(Flask):
    pass

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return super().default(obj)
# 创建应用
def create_app(test_config=None) -> Flask:
    app = SerpNews(__name__)

    # 从config文件中加载配置
    app.config.from_object(Configs())
    logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
    app.json_encoder = CustomJSONEncoder

    initialize_extensions(app)
    register_blueprints(app)
    return app


# 初始化flask相关的扩展
def initialize_extensions(app):
    ext_database.init_app(app)
    ext_migrate.init(app, db)


def register_blueprints(app:Flask):
    from controllers import bp as console_app_bp
    CORS(console_app_bp)
    app.register_blueprint(console_app_bp)

# fix windows platform
if os.name == "nt":
    os.system('tzutil /s "China Standard Time"')
else:
    os.environ['TZ'] = 'Asia/Shanghai'
    time.tzset()

#创建app应用
app = create_app()


# main函数入口
if __name__ == '__main__':

    app.run(host='0.0.0.0', port=5000)
